package com.anycc.cloud.core.util;

import com.anycc.cloud.common.exception.AnyccRuntimeException;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.Base64Utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.Key;

/**
 * 加密工具类
 */
@Component
public class CryptoUtil {

    /**
     * BCryptPasswordEncoder
     *
     * @return BCryptPasswordEncoder
     */
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * md5 encryption
     *
     * @param source source
     * @return String
     */
    public String md5(String source) {
        return (new Md5Hash(source)).toHex();
    }

    /**
     * decrypt source from front-end page(js encrypt)
     *
     * @param source    source
     * @param secretKey secretKey
     * @return String
     */
    public String decryptJsAES(String source, String secretKey) {
        try {
            Key key = this.generateAESSecretKey(secretKey);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//创建密码器
            cipher.init(2, key);//初始化为解密模式的密码器
            byte[] decryptDatas = cipher.doFinal(Base64Utils.decodeFromString(source));
            return new String(decryptDatas, "UTF-8");
        } catch (Exception exception) {
            throw new AnyccRuntimeException("CryptoJS AES解密异常", exception);
        }
    }

    private Key generateAESSecretKey(String secretKey) {
        try {
            Assert.notNull(secretKey, "AES加解密密钥不能为空");
            String secretKeyMD5 = this.md5(secretKey).substring(0, 16);
            return new SecretKeySpec(secretKeyMD5.getBytes("UTF-8"), "AES");
        } catch (UnsupportedEncodingException exception) {
            throw new AnyccRuntimeException("获取CryptoJS AES加解密密钥异常", exception);
        }
    }

    public static void main(String[] args){
        CryptoUtil cryptoUtil=new CryptoUtil();
        System.out.println(cryptoUtil.decryptJsAES("GxeRlTC/xaaaoPx1ViGfDA==","caogou"));
    }



}
